var $j = jQuery;
$j(document).ready(function(){
	
})

if(typeof Product=='undefined') {
    var Product = {};
}
/**************************** CONFIGURABLE PRODUCT **************************/
Product.Configpower = Class.create();
Product.Configpower.prototype = {
    initialize: function(config){
        this.config     = config;
        this.taxConfig  = this.config.taxConfig;
        this.settings   = $$('.super-attribute-area');
        this.state      = new Hash();
        this.selected_options      = new Array();
        this.prepriew_options      = new Array();
		
        this.all_options      = new Array();
        this.all_optionids      = new Array();
        this.priceTemplate = new Template(this.config.template);
        this.prices     = config.prices;
		this.childPorductImages = '';

        this.settings.each(function(element){
            Event.observe(element, 'click', this.configure.bind(this))
        }.bind(this));
		
		this.settings.each(function(element){
            Event.observe(element, 'mouseover', this.preview.bind(this))
        }.bind(this));
        
        this.settings.each(function(element){
            Event.observe(element, 'mouseout', this.moveout.bind(this))
        }.bind(this));
		
		//fill config
		this.settings.each(function(element){
            var attributeId = element.id.replace(/[a-z]*/, '');
			
			var attribute_option = explode( '_',attributeId );		
			if(attributeId && this.config.attributesoptions[attributeId]) {				
				element.config = this.config.attributesoptions[attributeId];
			}
			
			if( in_array( attributeId,this.all_optionids ) ){				
				this.all_options[this.all_options.length] = element;
				this.all_optionids[this.all_optionids.length] = attributeId;
			}
        }.bind(this));
        

        // Init settings dropdown
		/*
        var childSettings = [];
        for(var i=this.settings.length-1;i>=0;i--){
            var prevSetting = this.settings[i-1] ? this.settings[i-1] : false;
            var nextSetting = this.settings[i+1] ? this.settings[i+1] : false;
            if(i==0){
                this.fillSelect(this.settings[i])
            }
            else {
                this.settings[i].disabled=true;
            }
            $(this.settings[i]).childSettings = childSettings.clone();
            $(this.settings[i]).prevSetting   = prevSetting;
            $(this.settings[i]).nextSetting   = nextSetting;
            childSettings.push(this.settings[i]);
        }
		*/
        // try retireve options from url
        var separatorIndex = window.location.href.indexOf('#');
        if (separatorIndex!=-1) {
            var paramsStr = window.location.href.substr(separatorIndex+1);
            this.values = paramsStr.toQueryParams();
            this.settings.each(function(element){
                var attributeId = element.attributeId;
                element.value = (typeof(this.values[attributeId]) == 'undefined')? '' : this.values[attributeId];
                this.configureElement(element);
            }.bind(this));
        }
    },//end of construct
	
	setChildProductImages:function(json){
		this.childPorductImages = json;
	},
	moveout: function(event){
        var element = Event.element(event);
        var optionid = element.id.replace(/[a-z]*/, '');
        if( $('tip'+optionid+'_info') ){
        	$('tip'+optionid+'_info').style.display = 'none';
        }		
    },
	preview: function(event){
        var element = Event.element(event);
        var optionid = element.id.replace(/[a-z]*/, '');
        if( $('tip'+optionid+'_info') ){
        	$('tip'+optionid+'_info').style.display = 'block';
        }
		if( stristr( element.id,'optionv_' ) ){
			this.displayMainProductImage(element.config.products[0]);
		}
    },
	
	displayMainProductImage: function(id){
		$('main_image').src=this.childPorductImages[id]['resize'];
		$('main_image_a').href=this.childPorductImages[id]['org'];
	},
    configure: function(event){
        var element = Event.element(event);
        this.configureElement(element);
    },

    configureElement : function(element) {
		var optionid = element.id.replace(/[a-z]*/, '');		
		//this.config.attributes[attributeId]
        //this.reloadOptionLabels(element);		
        this.filterOption( element );
        //this.reloadPrice();
//      Calculator.updatePrice();
    },
	
	filterOption:function(element){
		var optoinid = element.id.replace(/[a-z]*/, '');
		var attribute_option = explode( '_',element.id.replace(/[a-z]*/, '') );
		var element_products = explode( ',',String(element.config.products) );
		var check_product_ids = element.config.products;
		//remove option in this.selected_options
		for (key in this.selected_options){
			if( key.match(/_\d+_\d+/) ){
				if(stristr( key,'_'+attribute_option[1]+'_' )){					
					//this.selected_options.splice(key, 1);
					if( key != optoinid ){
						delete this.selected_options[key];
					}	
				}
				/*else{
					//check clickable
					var product_ids = new Array();
					for (key in this.selected_options){
						if( key.match(/_\d+_\d+/) ){				
							if( !product_ids.length )
								product_ids = this.selected_options[key];
							else	product_ids = array_intersect( product_ids,this.selected_options[key] );
						}
					}
					var clickable = 1;
					if( product_ids.length ){
						product_ids = array_intersect( product_ids,element.config.products );
						clickable = 0;
						for( key in product_ids ){
							if( key.match(/\d+/) ){
								clickable = 1;
							}
						}
					}
					
					if( !clickable )
						return;
				}*/
			}
		}
		
		
		
		//set super attribute
		if( $('attribute'+attribute_option[1]).value > 0 && attribute_option[2] != $('attribute'+attribute_option[1]).value ){
			if(  $("color_"+attribute_option[1]+"_"+$('attribute'+attribute_option[1]).value)){
				$("option_"+attribute_option[1]+"_"+$('attribute'+attribute_option[1]).value).style.border = "1px dashed "+$("color_"+attribute_option[1]+"_"+$('attribute'+attribute_option[1]).value).value;
			}else{
				$("option_"+attribute_option[1]+"_"+$('attribute'+attribute_option[1]).value).style.border = "1px solid #336699";
			}
		}
		if(  $("color_"+attribute_option[1]+"_"+attribute_option[2])){
			$("option_"+attribute_option[1]+"_"+attribute_option[2]).style.border = "1px solid #e10085";
			$('totalShowColor').innerHTML = $("optionv_"+attribute_option[1]+"_"+attribute_option[2]).innerHTML;
		}else{
			$("option_"+attribute_option[1]+"_"+attribute_option[2]).style.border = "1px solid #e10085";
			$('totalShowSize').innerHTML = $("option_"+attribute_option[1]+"_"+attribute_option[2]).innerHTML;
		}
			
		$('attribute'+attribute_option[1]).value = attribute_option[2];
		//check if this options alreaky in all_options
		if( !this.selected_options[optoinid] ){
			this.selected_options[optoinid] = (element.config.products);
		}
		
		var product_ids = new Array();
		for (key in this.selected_options){
			if( key.match(/_\d+_\d+/) ){				
				if( !product_ids.length )
					product_ids = this.selected_options[key];
				else	product_ids = array_intersect( product_ids,this.selected_options[key] );
			}
		}
		//alert("product_ids:"+product_ids);
		//enable ,disable next options.
		this.settings.each(function(element){
			var optoinid = element.id.replace(/[a-z]*/, '');
			var attributeId = element.id;
			var attribute_option = explode( '_',element.id.replace(/[a-z]*/, '') );
			var attribute_option_2 = '';		
			
			if( element.config.products ){
				var option_available = 0;
				for( key in check_product_ids ){
					if( key.match(/\d+/) ){
						//alert( element.id + '--' + element.config.products );
						if( in_array( check_product_ids[key],element.config.products ) ){
							option_available = 1;
						}
					}
				}
				
				if( !option_available ){
					element.style.opacity = "0.4";
					element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=40,finishOpacity=100,style=0)';
					
					for (key in this.selected_options){
						if( key.match(/_\d+_\d+/) ){
							if(stristr( key,'_'+attribute_option[1]+'_' )){					
								//this.selected_options.splice(key, 1);
								if( key == optoinid ){
									delete this.selected_options[key];
									if(  $("color_"+attribute_option[1]+"_"+$('attribute'+attribute_option[1]).value)){
										$("option_"+attribute_option[1]+"_"+$('attribute'+attribute_option[1]).value).style.border = "1px dashed "+$("color_"+attribute_option[1]+"_"+$('attribute'+attribute_option[1]).value).value;
									}else{
										$("option_"+attribute_option[1]+"_"+$('attribute'+attribute_option[1]).value).style.border = "1px solid #336699";
									}
								}	
							}
						}
					}
					
				}else{
					element.style.opacity = "1";
					element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=100,finishOpacity=100,style=0)';
				}	
			}
		}.bind(this));
		
		
		
	},

    reloadOptionLabels: function(element){
        var selectedPrice;
        if(element.options[element.selectedIndex].config){
            selectedPrice = parseFloat(element.options[element.selectedIndex].config.price)
        }
        else{
            selectedPrice = 0;
        }
        for(var i=0;i<element.options.length;i++){
            if(element.options[i].config){
                element.options[i].text = this.getOptionLabel(element.options[i].config, element.options[i].config.price-selectedPrice);
            }
        }
    },

    resetChildren : function(element){
        if(element.childSettings) {
            for(var i=0;i<element.childSettings.length;i++){
                element.childSettings[i].selectedIndex = 0;
                element.childSettings[i].disabled = true;
                if(element.config){
                    this.state[element.config.id] = false;
                }
            }
        }
    },
	
    //fillSelect: function(element){
    //    var attributeId = element.id.replace(/[a-z]*/, '');
    /*    var options = this.getAttributeOptions(attributeId);
        this.clearSelect(element);
        element.options[0] = new Option(this.config.chooseText, '');

        var prevConfig = false;
        if(element.prevSetting){
            prevConfig = element.prevSetting.options[element.prevSetting.selectedIndex];
        }

        if(options) {
            var index = 1;
            for(var i=0;i<options.length;i++){
                var allowedProducts = [];
                if(prevConfig) {
                    for(var j=0;j<options[i].products.length;j++){
                        if(prevConfig.config.allowedProducts
                            && prevConfig.config.allowedProducts.indexOf(options[i].products[j])>-1){
                            allowedProducts.push(options[i].products[j]);
                        }
                    }
                } else {
                    allowedProducts = options[i].products.clone();
                }

                if(allowedProducts.size()>0){
                    options[i].allowedProducts = allowedProducts;
                    element.options[index] = new Option(this.getOptionLabel(options[i], options[i].price), options[i].id);
                    element.options[index].config = options[i];
                    index++;
                }
            }
        }
    },
	*/
    getOptionLabel: function(option, price){
        var price = parseFloat(price);
        if (this.taxConfig.includeTax) {
            var tax = price / (100 + this.taxConfig.defaultTax) * this.taxConfig.defaultTax;
            var excl = price - tax;
            var incl = excl*(1+(this.taxConfig.currentTax/100));
        } else {
            var tax = price * (this.taxConfig.currentTax / 100);
            var excl = price;
            var incl = excl + tax;
        }

        if (this.taxConfig.showIncludeTax || this.taxConfig.showBothPrices) {
            price = incl;
        } else {
            price = excl;
        }

        var str = option.label;
        if(price){
            if (this.taxConfig.showBothPrices) {
                str+= ' ' + this.formatPrice(excl, true) + ' (' + this.formatPrice(price, true) + ' ' + this.taxConfig.inclTaxTitle + ')';
            } else {
                str+= ' ' + this.formatPrice(price, true);
            }
        }
        return str;
    },

    formatPrice: function(price, showSign){
        var str = '';
        price = parseFloat(price);
        if(showSign){
            if(price<0){
                str+= '-';
                price = -price;
            }
            else{
                str+= '+';
            }
        }

        var roundedPrice = (Math.round(price*100)/100).toString();

        if (this.prices && this.prices[roundedPrice]) {
            str+= this.prices[roundedPrice];
        }
        else {
            str+= this.priceTemplate.evaluate({price:price.toFixed(2)});
        }
        return str;
    },

    clearSelect: function(element){
        for(var i=element.options.length-1;i>=0;i--){
            element.remove(i);
        }
    },

    getAttributeOptions: function(attributeId){
        if(this.config.attributes[attributeId]){
            return this.config.attributes[attributeId].options;
        }
    },

    reloadPrice: function(){
        var price = 0;
        for(var i=this.settings.length-1;i>=0;i--){
            var selected = this.settings[i].options[this.settings[i].selectedIndex];
            if(selected.config){
                price += parseFloat(selected.config.price);
            }
        }

        optionsPrice.changePrice('config', price);
        optionsPrice.reload();

        return price;

        if($('product-price-'+this.config.productId)){
            $('product-price-'+this.config.productId).innerHTML = price;
        }
        this.reloadOldPrice();
    },

    reloadOldPrice: function(){
        if ($('old-price-'+this.config.productId)) {

            var price = parseFloat(this.config.oldPrice);
            for(var i=this.settings.length-1;i>=0;i--){
                var selected = this.settings[i].options[this.settings[i].selectedIndex];
                if(selected.config){
                    price+= parseFloat(selected.config.price);
                }
            }
            if (price < 0)
                price = 0;
            price = this.formatPrice(price);

            if($('old-price-'+this.config.productId)){
                $('old-price-'+this.config.productId).innerHTML = price;
            }

        }
    }
}